package productlogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpProductLogic {
	return &UpProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpProductLogic) UpProduct(in *iotpb.UpProductReq) (*iotpb.UpProductResp, error) {
	product := in.GetParams()
	if product == nil || product.GetDeptId() == 0 || product.GetName() == "" ||
		product.GetTransportProtocol() == "" || product.GetMessageProtocol() == "" ||
		product.GetStorePolicy() == "" || product.GetDeviceType() == "" ||
		product.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新产品失败：参数缺失"),
			tool.GetErrMsgFormat("update product"), "params is not existed", in)
	}

	// 获取数据
	one, err := l.svcCtx.IotProductModel.FindOne(l.ctx, product.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update product"), err, in)
	}
	one.DeptId = product.GetDeptId()
	one.Name = product.GetName()
	one.Photo = product.GetPhoto()
	one.TransportProtocol = product.GetTransportProtocol()
	one.MessageProtocol = product.GetMessageProtocol()
	one.StorePolicy = product.GetStorePolicy()
	one.DeviceType = product.GetDeviceType()
	one.Describe = product.GetDescribe()
	one.UpdateUser = product.GetUpdateUser()

	// 更新
	err = l.svcCtx.IotProductModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update product"), err, in)
	}

	return &iotpb.UpProductResp{}, nil
}
